package com.Drools.其他;


import javax.script.*;
import java.io.FileNotFoundException;
import java.io.FileReader;


public class JavaScriptCompiler {
    public static void main(String[] args) throws ScriptException, NoSuchMethodException, FileNotFoundException {
        // 创建一个脚本引擎管理器
        ScriptEngineManager manager = new ScriptEngineManager();
        // 获取JavaScript脚本引擎
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        // 定义要预编译的JavaScript脚本
        String scriptCode = "function add(a, b) { return a + b; }";

        // 使用Compilable接口将脚本编译为可执行的对象
        Compilable compEngine = (Compilable) engine;
        CompiledScript compiledScript = compEngine.compile(scriptCode);
//        CompiledScript compiledScript1 = compEngine.compile(new FileReader("path/your/javascript/file.js"));

        // 执行预编译后的脚本
        Object result = compiledScript.eval();
        System.out.println("预编译结果: " + result);

        // 调用预编译后的函数
        Invocable invEngine = (Invocable) engine;
        Object res = invEngine.invokeFunction("add", 2, 3);  
        System.out.println("函数调用结果: " + res);
    }



}

